﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MREO.data;
using System.Data.SqlServerCe;

namespace MREO.gui
{
    public partial class fUsers : Form
    {
        DataTable dtUsers;

        Connection Conn = new Connection();
        SqlCeDataAdapter adapter = new SqlCeDataAdapter();
        SqlCeCommand command = null;

        public fUsers()
        {
            InitializeComponent();

            fullDtUsers();
        }

        private void fullDtUsers()
        {
            dtUsers = new DataTable();

            try
            {
                Conn.con.Open();

                command = new SqlCeCommand("SELECT id, fam, im, otch, lvl, pwd " +
                                            " FROM users ORDER BY lvl"
                                            , Conn.con);
                adapter.SelectCommand = command;
                adapter.Fill(dtUsers);
            }
            catch (Exception exc) { throw new Exception(exc.Message); }
            finally
            {
                command.Dispose();
                adapter.Dispose();
                if (Conn.con.State == ConnectionState.Open)
                    Conn.con.Close();
            }
        }

        private void createTree()
        {
            string strSearch = string.Empty;

            treeView_users.Nodes.Clear();

            foreach (DataRow dr in dtUsers.AsEnumerable())
            {
                TreeNode[] node = null;

                switch (dr["lvl"].ToString())
                {
                    case "0":
                        node = treeView_users.Nodes.Find("Пользователи", false);
                        if (node.Count() == 0)
                        {
                            treeView_users.Nodes.Add("Пользователи").Name = "Пользователи";
                            strSearch = "Пользователи";
                        }
                        break;

                    case "1":
                        node = treeView_users.Nodes.Find("Администраторы", false);
                        if (node.Count() == 0)
                        {
                            treeView_users.Nodes.Add("Администраторы").Name = "Администраторы";
                            strSearch = "Администраторы";
                        }
                        break;
                }

                node = treeView_users.Nodes.Find(strSearch, false);

                if (node.Count() > 0)
                {
                    Users oUser = new Users();

                    oUser._id = int.Parse(dr["id"].ToString());
                    oUser._fam = dr["fam"].ToString();
                    oUser._im = dr["im"].ToString();
                    oUser._otch = dr["otch"].ToString();
                    oUser._lvl = int.Parse(dr["lvl"].ToString());
                    oUser._pwd = dr["pwd"].ToString();

                    node[0].Nodes.Add(oUser._fam + " " + oUser._im + " " + oUser._otch).Tag = oUser;
                }
            }
        }

        private void toolStripButton_add_Click(object sender, EventArgs e)
        {
            fUsers_AddEdit fAddEdit = new fUsers_AddEdit();
            fAddEdit.Text = "Новая учетная запись";
            if (fAddEdit.ShowDialog() != DialogResult.OK) return;

            fullDtUsers();
            createTree();
        }

        private void toolStripButton_edit_Click(object sender, EventArgs e)
        {
            fUsers_AddEdit fAddEdit = new fUsers_AddEdit();
            fAddEdit.oUser = treeView_users.SelectedNode.Tag as Users;
            fAddEdit.Text = "Редактирование: " + fAddEdit.oUser._fam;
            if (fAddEdit.ShowDialog() != DialogResult.OK) return;

            fullDtUsers();
            createTree();
        }

        private void toolStripButton_del_Click(object sender, EventArgs e)
        {
            Users oUser = treeView_users.SelectedNode.Tag as Users;

            if (oUser._id == GValues._userID)    // Нельзя удалить под кем вошли
            {
                MessageBox.Show("Вы не можете удалить запись о пользователе под которым вошли в систему.");
                return;
            }

            if (MessageBox.Show("Вы действительно хотите удалить запись о пользователе \"" + 
                    oUser._fam + " " + oUser._im.Substring(0, 1) + ". " + oUser._otch.Substring(0, 1) + ".\"", 
                    "Удаление записи", 
                    MessageBoxButtons.YesNo) 
                == DialogResult.Yes)
            {
                try
                {
                    Conn.con.Open();

                    command = new SqlCeCommand("DELETE FROM users WHERE id = @id"
                                                , Conn.con);
                    command.Parameters.Add("@id", SqlDbType.Int).Value = oUser._id;

                    command.ExecuteNonQuery();
                }
                catch (Exception exc) { throw new Exception(exc.Message); }
                finally
                {
                    command.Dispose();
                    adapter.Dispose();
                    if (Conn.con.State == ConnectionState.Open)
                        Conn.con.Close();
                }
            }

            fullDtUsers();
            createTree();
        }

        private void treeView_users_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView_users.SelectedNode.Tag == null)
            {
                toolStripButton_add.Enabled = true;
                toolStripButton_edit.Enabled = false;
                toolStripButton_del.Enabled = false;
            }
            else
            {
                toolStripButton_add.Enabled = false;
                toolStripButton_edit.Enabled = true;
                toolStripButton_del.Enabled = true;
            }
        }

        private void fUsers_Shown(object sender, EventArgs e)
        {
            createTree();
        }
    }
}
